//
//  AppDelegate.swift
//  mlz
//
//  Created by 吕凌 on 2018/4/3.
//  Copyright © 2018年 吕凌. All rights reserved.
//

import UIKit
import WeexSDK

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate, XGPushDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?
    var viewController: ViewController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        Thread.sleep(forTimeInterval: 0.8)
        WXAppConfiguration.setAppGroup("mlz")
        WXAppConfiguration.setAppName("咪族购")
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        WXAppConfiguration.setAppVersion(currentVersion)
//        WeexLog.setLogLevel(WXLogLevel.error)
        var customerEvn:[String:Any] = [:]
        #if DEBUG
        customerEvn["debug"] = true
        #else
        customerEvn["debug"] = false
        #endif
        customerEvn["bundleJsLocalDir"] = "file://" + BundleJsService.instance.dir()
        WXSDKEngine.setCustomEnvironment(customerEvn)
        WXSDKEngine.registerModule("event", with: NSClassFromString("WXEventModule"))
        WXSDKEngine.registerModule("aliTradeService", with: WXAliTradeServiceModule.self)
        WXSDKEngine.registerModule("weixinApi", with: WXWeixinApiModule.self)
        WXSDKEngine.registerModule("base64", with: WXBase64Module.self)
        WXSDKEngine.registerModule("album", with: WXAlbumModule.self)
        WXSDKEngine.registerModule("bundleJsService", with: WXBundleJsServiceModule.self)
        WXSDKEngine.registerModule("utils", with: WXUtilsModule.self)
        WXSDKEngine.registerModule("pushService", with: WXPushServiceModule.self)
        WXSDKEngine.registerModule("keplerApi", with: WXKeplerApiModule.self)
        WXSDKEngine.registerModule("application", with: WXApplication.self)
        WXSDKEngine.registerModule("pddService", with: WXPddServiceModule.self)
        WXSDKEngine.registerModule("alipay", with: WXAlipayModule.self)
        // register extra component
        WXSDKEngine.registerComponent("divExtra", with: NSClassFromString("WXDivExtraComponent"))
        // register handler
        WXSDKEngine.registerHandler(WXImageLoaderDefaultImplement(), with:NSProtocolFromString("WXImgLoaderProtocol"))
        
        //init WeexSDK
        WXSDKEngine.initSDKEnvironment()

        AlibcTradeSDK.sharedInstance().setDebugLogOpen(true)
        AlibcTradeSDK.sharedInstance().setIsvVersion("beijing")
//        AlibcTradeSDK.sharedInstance().setISVCode("25237611")
//        AlibcTradeSDK.sharedInstance().setEnv(AlibcEnvironment.release)
        AlibcTradeSDK.sharedInstance().asyncInit(success: {() in
            print("AliTrade初始化成功")
        }, failure: {(msg) in
            print(msg)
        })
        
//        ALBBSDK.sharedInstance()?.setAppkey("25185222")
//        ALBBSDK.sharedInstance()?.albbsdkInit()
//        ALBBSDK.sharedInstance()?.setLoginResultHandler({ (session) in
//            session?.getUser()
//        })

        WXSDKEngine.registerComponent("map", with: WXMapComponent.self)
        WXApi.registerApp("wx1ec9634f2b3eac50")
        self.registerAppNotificationSettings()
        //初始化开普勒
        KeplerApiManager.sharedKPService().asyncInitSdk("bb63770aec0143549b07a8abee71c2d0", secretKey: "9b728135604a48dfa568abfaa9eb0a15",
                sucessCallback: {
                    () -> Void in
                    print("kepler初始化成功")
                }, failedCallback: {
            (error) -> Void in
            print("kepler初始化失败")
        });
        XGPush.defaultManager().isEnableDebug = true
        XGPush.defaultManager().startXG(withAppID: 2200319295, appKey: "I8UI1H46Y8UF", delegate: self)
        if(false) {
            self.showDl()
        } else {
            self.viewController = ViewController()
            self.viewController?.main = true
            let now = Date()
            let timeInterval:TimeInterval = now.timeIntervalSince1970
            #if DEBUG
            viewController?.url = URL.init(string: "http://192.168.31.174/mz/index.js?_=" + String(timeInterval))
            #else
            viewController?.url = URL.init(string: "https://bundlejs.mizugou.com/ios/"+currentVersion+"/index.js?_=" + String(timeInterval) )
            #endif
            window = UIWindow.init(frame: UIScreen.main.bounds)
            window?.backgroundColor = UIColor.white
            window?.rootViewController = UINavigationController.init(rootViewController: viewController!)
        }
        return true
    }
    
    func showDl() {
        self.window = UIWindow.init(frame: UIScreen.main.bounds);
        self.window?.frame = UIScreen.main.bounds;
        self.window?.makeKeyAndVisible();
        let defaults = UserDefaults.standard;
        let cookieName = defaults.string(forKey: "kCookie");
        if (cookieName != nil) {
            self.window?.rootViewController = EastMarketTabBarController.init();
        } else {
            
            let nav = UINavigationController.init(rootViewController: LoginViewController.init());
//            UINavigationBar.appearance().setBackgroundImage()
            
            //设置导航栏的title颜色以及大小
            UINavigationBar.appearance().titleTextAttributes = [
                NSAttributedString.Key.foregroundColor: UIColor.white,
                NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 22.0)
            ]
            
            //设置导航栏的状态栏前景色
            UIApplication.shared.statusBarStyle = .lightContent
//            self.window?.rootViewController?.preferredStatusBarStyle = UIStatusBarStyle.lightContent;
            self.window?.rootViewController = nav;
        }
        
       UIApplication.shared.statusBarStyle = .lightContent
    }
    
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        if url.host == "safepay" {
//            AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: {
//                (resultDic) -> Void in
//                if((StaticContext.alipayCallback) != nil) {
//                    StaticContext.alipayCallback!(resultDic, false)
//                    StaticContext.alipayCallback = nil
//                }
//            })
            return true
        }
        if(AlibcTradeSDK.sharedInstance().application(application, open: url, options: nil)) {
            return true
        }
        return WXApi.handleOpen(url, delegate: self)
    }
                                                                                                                                                                                                                                         
//    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
//        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
//    }
//    
//    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
//        return WXApi.handleOpen(url, delegate: self)
//    }
    
    func onReq(_ req: BaseReq!) {
        //onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
    }
    func onResp(_ resp: BaseResp!) {
        //如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
        if (resp.isKind(of: SendAuthResp.self)) {
            let authResp: SendAuthResp = (resp as! SendAuthResp)
            if(authResp.code == nil) {
                self.viewController?.weexInstance?.fireGlobalEvent("weixinAuth", params: [:]);
                return;
            }
            let params:[String:AnyObject] = ["code": authResp.code as AnyObject, "state": authResp.state as AnyObject]
            self.viewController?.weexInstance?.fireGlobalEvent("weixinAuth", params: params);
        }
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        if #available(iOS 10.0, *) {
            UIApplication.shared.applicationIconBadgeNumber = -1
        } else {
            let localNotification = UILocalNotification.init()
            localNotification.fireDate = Date.init()
            localNotification.applicationIconBadgeNumber = -1
            UIApplication.shared.scheduleLocalNotification(localNotification)
        }
        
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    private func registerAppNotificationSettings() {
        if #available(iOS 10.0, *) {
            let notifiCenter = UNUserNotificationCenter.current()
            notifiCenter.delegate = self
            let types = UNAuthorizationOptions(arrayLiteral: [.alert, .badge, .sound])
            notifiCenter.requestAuthorization(options: types) { (flag, error) in
                if flag {
                    
                }else{
                    
                }
            }
        } else { //iOS8,iOS9注册通知
            let setting = UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
        }
        
        UIApplication.shared.registerForRemoteNotifications()
    }
    
    internal func xgPushDidFinishStart(_ isSuccess: Bool, error: Error?) {
        
    }
    
    internal func xgPushDidRegisteredDeviceToken(_ deviceToken: String?, error: Error?) {
        print("信鸽推送deviceToken:" + deviceToken!)
    }
    
    @available(iOS 10.0, *)
    func xgPush(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification?, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground")
        // custom code to handle push while app is in the foreground
        print("\(String(describing: notification?.request.content.userInfo))")
        XGPush.defaultManager().reportXGNotificationInfo((notification?.request.content.userInfo)!)
        self.viewController?.weexInstance?.fireGlobalEvent("notification", params: notification?.request.content.userInfo);
        completionHandler(UNNotificationPresentationOptions(rawValue: UNNotificationPresentationOptions.badge.rawValue | UNNotificationPresentationOptions.sound.rawValue | UNNotificationPresentationOptions.alert.rawValue));
    }
    
    @available(iOS 10.0, *)
    func xgPush(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse?, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Handle push from background or closed")
        // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
        print("\(String(describing: response?.notification.request.content.userInfo))")
        self.viewController?.weexInstance?.fireGlobalEvent("notification", params: response?.notification.request.content.userInfo);
        NotificationContext.setUserInfo(params: response?.notification.request.content.userInfo as! [String : Any])
        XGPush.defaultManager().reportXGNotificationInfo((response?.notification.request.content.userInfo)!)
    }
    
}

